package com.yy.chapter5.controller;

import com.yy.chapter5.Utils.FileUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;

/**
 * @author yangyao
 * @Description: FileController
 * @date 2018/10/22 09:46
 */
@Controller
@RequestMapping(value = "/file")
public class FileController {

    /**
     * 到达单文件上传页面
     * @return
     */
    @RequestMapping(value = "/singleFile",method = RequestMethod.GET)
    public String singleFile(){
        return "fileUpload";
    }

    /**
     * 单文件处理
     * @param file
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/upload")
    public String upload(MultipartFile file){
        //文件上传的目录
        String uploadDir = "D:\\"+"chapter5\\"+"upload";
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //文件名
        String fileName = file.getOriginalFilename();
        File uploadFileName = new File(dir + File.separator + fileName);
        try {
            file.transferTo(uploadFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传成功";
    }

    /**
     * 到达多文件上传页面
     * @return
     */
    @RequestMapping(value = "/multipartFile",method = RequestMethod.GET)
    public String multipartFile(){
        return "multipartFile";
    }

    /**
     * 多文件上传
     * @param file
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping(value = "/multiPartUpload")
    public String multiPartUpload(MultipartFile[] file) throws Exception{
        //文件上传的目录
        String uploadDir = "D:\\"+"chapter5\\"+"upload";
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        for (int i = 0; i < file.length; i++) {
            FileUtil.uploadFile(uploadDir,file[i]);
        }
        return "上传成功";
    }
}
